package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.tool.R;
import com.itheima.tool.SMSUtils;
import com.itheima.tool.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService service;

    @PostMapping("login")
    public R login(@RequestBody Map map,HttpSession session){
        String phonenumber = map.get("phonenumber").toString();

        //code为验证码
        String code = map.get("code").toString();

        Object getCodeInSession = session.getAttribute("code");

        if (getCodeInSession!=null&&getCodeInSession.equals(code)){

            LambdaQueryWrapper<User> ulqw = new LambdaQueryWrapper<>();

            ulqw.eq(User::getPhone,phonenumber);

            User getByulqw = service.getOne(ulqw);

            if (getByulqw!=null){
                User user = new User();
                user.setStatus(1);
                user.setPhone(phonenumber);
                service.save(user);
            }
            session.setAttribute("user",getByulqw.getId());
            return R.success(getByulqw);
        }
        return R.error("验证码错误");
    }

    @PostMapping("/sendMsg")
    public R check(@RequestBody User user, HttpSession session){
        String phonenumber = user.getPhone();
        if (!StringUtils.isEmpty(phonenumber)){
            String code = ValidateCodeUtils.generateValidateCode(6).toString();

            SMSUtils.sendMessage("","",phonenumber,code);

            session.setAttribute(phonenumber,code);
            return R.success();
        }

        return R.error("发送失败");
    }
}
